package com.yangyu.service;

import com.yangyu.currency.Constant;
import com.yangyu.currency.StatusCode;
import com.yangyu.mapper.UserMapper;
import com.yangyu.message.BaseRsp;
import com.yangyu.message.user.MakeCodeVo;
import com.yangyu.pojo.User;
import com.yangyu.util.RedisUtil;
import com.yangyu.util.SendEmailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Service
public class RegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private RedisUtil redisUtil;

    public BaseRsp makeCheckCode(MakeCodeVo makeCodeVo) {
        List<User> users;
        users = userMapper.checkEmail(makeCodeVo.getEmail());
        if (!CollectionUtils.isEmpty(users)) {
            return new BaseRsp(StatusCode.UserErrorCode.EMAIL_REGISTERED, "邮箱已被注册");
        }
        long expireTime = redisUtil.getExpire(Constant.Redis.SEND_VERIFICATION_CODE + makeCodeVo.getEmail());
        if (expireTime >= 0) {
            return new BaseRsp(StatusCode.UserErrorCode.CODE_SEND_ERROR, "验证码已发送，请于" + expireTime + "秒后重试");
        }
        // 生成验证码
        int code = (int)((Math.random() * 9 + 1) * 100000);
        redisUtil.set(Constant.Redis.VERIFICATION_CODE + makeCodeVo.getEmail(), code, 5 * 60);
        redisUtil.set(Constant.Redis.SEND_VERIFICATION_CODE + makeCodeVo.getEmail(), code, 60);

        try {
            SendEmailUtil.sendEmail(mailSender, makeCodeVo.getEmail(), code);
        } catch (MailException e) {
            log.error("发送邮件失败", e);
            return new BaseRsp(StatusCode.UserErrorCode.SEND_CODE_FAILED, "发送验证码失败");
        }

        return new BaseRsp("发送成功");
    }
}
